
package com.sl.au.service.impl;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import com.sl.au.entity.M2R;
import com.sl.au.entity.Module;
import com.sl.au.entity.ModuleInfo;
import com.sl.au.entity.Role;
import com.sl.au.repository.M2RRepository;
import com.sl.au.repository.ModuleRepository;
import com.sl.au.service.M2RService;
import com.sl.au.service.ModuleService;

@Service("ModuleService")
@Transactional
public class ModuleServiceImpl extends BaseServiceImpl implements ModuleService {

	@Value("${server.context-path}")
	private String contextPath;
	
	@Autowired
	ModuleRepository moduleRepository;
	@Autowired
	M2RRepository m2rRepository;
	@Autowired
    M2RService m2rService;

	@Override
	public List<Module> getPage(int start, int length, String key, String orderName, String dir) {
		Page<Module> pages = null;
		Pageable pageable = new PageRequest(start / length, length, Sort.Direction.DESC, "id");
		String i = "2";
		pages = moduleRepository.getData(i, pageable);
		return pages.getContent();
	}

	@Override
	public List<Module> getModules(int start, int length, String key, String orderName, String dir) {
		Page<Module> pages = null;
		Pageable pageable = new PageRequest(start / length, length, Sort.Direction.DESC, "groupId");
		pages = moduleRepository.getModuleName(key, pageable);
		// pages = moduleRepository.findByModuleNameLike(moduleName, pageable);
		return pages.getContent();
	}

	@Override
	public List<Module> getAllNodes(String menuId) {
		List<Module> nodes = new ArrayList<Module>();
		if (StringUtils.hasText(menuId)) {
			String key = menuId.replaceAll("\\s+", "");
			if (StringUtils.hasText(key)) {
				nodes = moduleRepository.findBymenuId(menuId);

			}
		}

		return nodes;
	}

	@Override
	public List<Module> getNextNodes(String pId) {
		List<Module> nodes = new ArrayList<Module>();
		if (StringUtils.hasText(pId)) {
			String key = pId.replaceAll("\\s+", "");
			if (StringUtils.hasText(key)) {
				nodes = moduleRepository.findByparentId(pId);
			}
		}
		return nodes;
	}

	@Override
	public List<Map<String, Object>> getNodeMap(List<Module> node) {
		List<Map<String, Object>> nodeMap = new ArrayList<Map<String, Object>>();
		for (Module p : node) {
			if (null != p) {
				Map<String, Object> map = new HashMap<String, Object>();
				map.put("id", p.getId());
				map.put("parentId", p.getParentId());
				if (p.getParentId().equals("0")) {
					String menuelId = p.getMenuId();
					if (StringUtils.hasText(menuelId)) {
						map.put("name", p.getModuleName());
						map.put("nocheck", true);
					}
				} else {
					map.put("name", String.valueOf(p.getMenuIndex())+p.getModuleName());
				}
				if (StringUtils.hasText(p.getIsParent())) {
					map.put("isParent", p.getIsParent());
				}
				if (StringUtils.hasText(p.getIsOpen())) {
					map.put("open", p.getIsOpen());
				}
				nodeMap.add(map);
			}
		}
		return nodeMap;
	}

	@Override
	public void saveNode(String menuId, String parentId, String id, Module node) {
		int nodes;
		if (null != parentId) {
			nodes = moduleRepository.setModuleNode(menuId, parentId, id);
		}
		return;
	}

	@Override
	public void setParentNode(String parentId, String aTrue) {
		Module oldNode = new Module();
		oldNode = moduleRepository.findById(parentId);
		if (null != oldNode) {
			oldNode.setIsParent(aTrue);
			oldNode.setIsOpen(aTrue);
		}
	}

	@Override
	public void deleteNodes(String[] ids) {
		int node;
		if (ids.length > 0) {
			for (String id : ids) {
				if (StringUtils.hasText(id)) {
					String menuId = "2";
					String parentId = "";
					node = moduleRepository.setModuleNode(menuId, parentId, id);
					List<M2R> m2rs=m2rService.getRepository().findByModuleId(id);
		  			m2rService.getRepository().deleteInBatch(m2rs);
				}
			}
		}
		return;
	}

	@Override
	public int sureParent(String id) {
		List<Module> nodes = new ArrayList<Module>();
		int isParent;
		if (StringUtils.hasText(id)) {
			String key = id.replaceAll("\\s+", "");
			if (StringUtils.hasText(key)) {
				nodes = moduleRepository.findByparentId(key);
			}
		}
		if (nodes.size() > 0) {
			isParent = 1;
		} else {
			isParent = 0;
		}
		return isParent;
	}

	public ModuleRepository getRepository() {
		return this.moduleRepository;
	}

	@Override
	@Transactional(readOnly=true)
	public List<ModuleInfo> getModulesInfo(Role role) {
		String roleId = role.getId();

		List<ModuleInfo> list = new ArrayList<ModuleInfo>();
		ModuleInfo moduleInfo = null;
		List<Module> subModules = null;
		Module self = null;
		Module mt;
		Set<Module> temp= this.moduleRepository.findModulesByRoleId(roleId);
		Set<Module> modules = new HashSet<>();
		for(Module a:temp){
			mt=new Module();
			BeanUtils.copyProperties(a, mt);
			modules.add(mt);
		}
		//得到一级菜单项
		List<Module> menuTop = modules.stream().filter(m -> m.getMenuLevel() == 1)
				.sorted(Comparator.comparing(Module::getMenuIndex))
				.collect(Collectors.toList());

		menuTop.forEach(row->{
			String target=row.getTarget();
			if(!target.equals("#"))
					row.setTarget(this.contextPath+target);
			});
		
		
		for (Module m : menuTop) {
			moduleInfo = new ModuleInfo();
			
			moduleInfo.setSelf(m);

			// 得到二级菜单项
			
			//subModules = this.moduleRepository.findByparentIdOrderByMenuIndex(m.getId());
			subModules=modules.stream()
					.filter(r->r.getParentId().equals(m.getId())&&r.getMenuLevel()==2)
					.sorted(Comparator.comparing(Module::getMenuIndex))
					.collect(Collectors.toList());
			subModules.stream()				
			.forEach(row->{
				//读取每个模块的操作权限
				M2R m2r=m2rRepository
						.findByRoleIdAndModuleId(roleId, row.getId());
				if(null!=m2r){
					row.setCanRead(m2r.isReadOnly());
					row.setCanAdd(m2r.isAddOnly());
					row.setCanDelete(m2r.isDeleteOnly());
					row.setCanModify(m2r.isModifyOnly());
					row.setCanOther1(m2r.isOther1Only());
					row.setCanOther2(m2r.isOther2Only());
				}
				String target=row.getTarget();
				if(!target.equals("#"))
						row.setTarget(this.contextPath+target);
				});
			if (null == subModules || subModules.size()<1) {
				// 没有二级菜单
				moduleInfo.setHas3Menu(false);
				moduleInfo.setHasChildren(false);
			} else {
				moduleInfo.setHas3Menu(false);
				moduleInfo.setHasChildren(true);
				
				
				
			} // end of if

			// 三级菜单确认

			 List<ModuleInfo> m3List=new ArrayList<>();
			for (Module m2 : subModules) {
				if (null == m2.getIsParent())
					continue;
				// 得到三级菜单项
				subModules = this.moduleRepository.findByparentIdOrderByMenuIndex(m2.getId());
				if (null == subModules)
					continue;
				ModuleInfo moduleInfo2 = new ModuleInfo();
				moduleInfo.setHas3Menu(true);
				moduleInfo.setHasChildren(false);
				moduleInfo2.setSelf(m2);
				
				
				m3List.add(moduleInfo2);

			}
			//为每个模块设置操作控制
			
			moduleInfo.setModules(subModules);
			
			if(m3List.size()>0) moduleInfo.setModules2(m3List);
			

			list.add(moduleInfo);
		} // end of first for
		return list;
	}

	@Override
	public List<Module> getSimpleModulesByRole(String roleId) {
		List<Module> list=new ArrayList<>();
		Set<Module> origin=this.moduleRepository.findModulesByRoleId(roleId);
		Module tm=null;
		M2R m2r;
		if(null!=origin && origin.size()>0){
			for(Module m:origin){
				tm=new Module();
				tm.setId(null);
				tm.setCreateTime(null);
				tm.setUpdateTime(null);
				tm.setModuleName(m.getModuleName());
				tm.setName(m.getName());
				//读取每个模块的操作权限
			    m2r=m2rRepository
						.findByRoleIdAndModuleId(roleId, m.getId());
				if(null!=m2r){
					tm.setCanRead(m2r.isReadOnly());
					tm.setCanAdd(m2r.isAddOnly());
					tm.setCanDelete(m2r.isDeleteOnly());
					tm.setCanModify(m2r.isModifyOnly());
					tm.setCanOther1(m.isCanOther1());
					tm.setCanOther2(m.isCanOther2());
				}
				list.add(tm);
			}
		}
		return list;
	}
}
